package com.fckbug.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;


public class CharFilter implements Filter {// 过滤掉request里包含的非法字符，如：'
	private String[] characterParams = null;    
	private boolean OK = true;
	private Logger logger = Logger.getLogger(CharFilter.class);

	public void init(FilterConfig filterConfig) throws ServletException {
		String str= filterConfig.getInitParameter("characterParams");        
		if(str==null||"".equals(str)){            
			OK = false;        
		}else{            
			this.characterParams = filterConfig.getInitParameter("characterParams").split(",");        
		}
	}

	public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
		HttpServletRequest servletrequest = (HttpServletRequest) request;
    	HttpServletResponse servletresponse = (HttpServletResponse) response;
    	if (OK) {// 过滤字符串为0个时 不对字符过滤
    		boolean status = false;
	    	java.util.Enumeration params = request.getParameterNames();
	    	String param = "";
	    	String paramValue = "";
	    	while (params.hasMoreElements()) {
	    		param = (String) params.nextElement();
	    		String[] values = request.getParameterValues(param);
	    		paramValue = "";
	    			for (int i = 0; i < values.length; i++)
	    				paramValue = paramValue + values[i];
	    			for (int i = 0; i < characterParams.length; i++)
	    				if (paramValue.indexOf(characterParams[i]) >= 0) {
	    					status = true;
	    					break;
	    				}
	    			if (status)                    
	    				break;            
	    	}
	    	if (status) {
	    		logger.warn(servletrequest.getRemoteAddr() + "-" + servletrequest.getRequestURL() + "输入值不合法");
	    		servletresponse.sendRedirect("/info/error.jsp?c=1");
	    	}
    	}
		chain.doFilter(request, response);
    }

	public void destroy() {
	}
}
